package com.og.converter;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;

import com.og.backingbean.Type;
import com.og.managedbean.ListBean;

/**
 * @author Renaud DIANA
 *
 */
@Named("typeConverterBean")
@SessionScoped
@FacesConverter("typeConverter")
public class TypeConverter implements Converter, Serializable {

	private static final long serialVersionUID = 1L;
	
	// Log4j	 
	private static final Logger	log	= Logger.getLogger(TypeConverter.class);
	
	/* Dependency injection */	
    // BackingBean	
	@Inject
    private ListBean list;
	
	/* -------------------- */
	
	/**
	 * Default constructor
	 */
	public TypeConverter() {
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		log.debug("String Value = " + value.toString());		
		if (value.equals("Select One")) {
            return null;
        }

        for (Type type : list.getListType()) {
            if (String.valueOf(type.getIdType()).equals(value)) { // !!equals method must be overridden in Type class!!
                return type;
            }
        }

        throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to Type", value)));
    }

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		log.debug("Object Value = " + value.toString());
		return (value instanceof Type) ? String.valueOf(((Type) value).getIdType()) : null;
	}

}
